<template>
  <div>
    <!--客户信息-->
    <FormPanel
      ref="formList"
      :list="formList"
      formType="add"
      :cols="3"
      :labelWidth="105"
      :isSubmitBtn="false"
    />


    <!-- 列表  -->
    <el-tabs v-model="activeName" class="outer">
      <el-tab-pane label="车辆信息" name="first">
        <FilterTable
          ref="table"
          :columns="vehicle"
          :isSelectColumn="false"
          :params="fetchParams"
          :height="120"
          :onColumnsChange="vehicle => (this.vehicle = vehicle)"
        />
      </el-tab-pane>
    </el-tabs>
    <!--
    <template>
     <div> -->
      <!--列表-->
      <!-- <FilterTable
        ref="vehicle"
        :fetchapi="fetchApi"
        :columns="vehicle"
        :params="fetchParams"
        :datakey="'rows'"
        :height="100"
        :onColumnsChange="vehicle => (this.vehicle = vehicle)"
        :isSelectColumn="false"
      />
    </div>
    </template> -->

     <!--回访内容-->
    <FormPanel
      ref="formList1"
      :list="formList1"
      formType="add"
      :cols="3"
      :labelWidth="105"
      :isSubmitBtn="false"
    />
    <!--操作按钮-->
    <div
      :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'right'
        }"
    >
      <el-button type="primary" :loading="confirmBtnLoading" @click="save()">保存</el-button>
      <el-button type="primary"  @click="exhale('0')">智能外呼</el-button>
      <el-button type="primary"  @click="exhale('00')">加0外呼</el-button>
      <el-button @click="closeDialog">关闭</el-button>
    </div>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import dictCode from '@/utils/dictCode';
// 生日提醒
import { getOwnerVehicle , saveRemind}  from '@/api/customerRepair/customerCare/birthdayRemind';
import {  getSeries, getModel } from '@/api/customerRepair/customerCare/insuranceDueRemind/index';

export default {
  mixins: [dictionary],
   props: {
    type: {
      type: String,
      default: 'add'
    },
    remindData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // 表单绑定
      formList: this.createFormList(),
      formList1:this.createFormList1(),
      confirmBtnLoading: false,
      vehicle: this.getvehicle(),
      fetchParams: {},
      activeName: 'first',
      ownerNo:'',
      remindId:'',
      /* 呼叫中心所需字段----begin */
      afterVal: '',
      HFDH: '',
      ctiUrl:'',
      callid:''
      /* 呼叫中心所需字段 ----end*/
    };
  },
  created() {
    this.init();
    this.querySeries();
    this.queryModel();
  },
  mounted() {
    this.after();
  },
  methods: {
     init() {
      this.ownerNo = this.remindData.ownerNo;
      this.formList.forEach(x => {
        x.initialValue = this.remindData[x.fieldName];
      });
      if(this.type=="edit"){
        this.remindId = this.remindData.remindId;
      }
      // 查询车辆信息
      this.selectList();
    },
/** 返回表单对象 */
    createFormList() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '车主信息'
        },
        {
          type: 'INPUT',
          label: '车主编码',
          fieldName: 'ownerNo',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车主名称',
          fieldName: 'cusName',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车主手机',
          fieldName: 'mobile',
          disabled: true
         },
        {
          type: 'INPUT',
          label: '车主电话',
          fieldName: 'phone',
          disabled: true
         },
         {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'linkMan',
          disabled: true
         },
         {
          type: 'INPUT',
          label: '联系人电话',
          fieldName: 'linkTel',
          disabled: true
         },
         {
          type: 'INPUT',
          label: '联系人手机',
          fieldName: 'linkMobile',
          disabled: true
         }

      ];
    },
    getvehicle() {
      return [
        {
          title: '车系',
          dataIndex: 'SERIES',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: []
        },
        {
          title: '车型',
          dataIndex: 'MODEL',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: []
        },

        {
          title: '购车日期',
          dataIndex: 'SALES_DATE',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd'
        }
      ];
    },
    createFormList1(){
      return [
        {
          type: 'BREAK_SPACE',
          label: '关怀信息'
        },
        {
          type: 'SELECT',
          label: '关怀状态',
          fieldName: 'remindStatus',
          initialValue: '',
          itemList: this.createDictList('8206'),
          rules: [{ required: true, message: '请选择关怀状态' }]
        },
        {
          type: 'SELECT',
          label: '关怀原因',
          fieldName: 'remindFailReason',
          initialValue: '',
          itemList: this.createDictList('8207'),
          rules: [{ required: true, message: '请选择关怀原因' }]
        },
        {
          type: 'SELECT',
          label: '关怀结果',
          fieldName: 'remindResult',
          initialValue: '',
          itemList: this.createDictList('1075'),
          rules: [{ required: true, message: '请选择关怀结果' }]
        },
        {
          type: 'CHECKBOX',
          label: '免打扰',
          fieldName: 'isDistruble',
          // initialValue: '10041001',
          options: { trueValue: 10041001, falseValue: 10041002 },
        },
         {
          type: 'CHECKBOX',
          label: '需再次关怀',
          fieldName: 'ifNext',
          // initialValue: '10041001',
          options: { trueValue: 10041001, falseValue: 10041002 },
          change: val => this.selectChangeGh(val)
        },
        {
          type: 'DATE',
          label: '下次关怀日期',
          fieldName: 'nextDate',
          initialValue: '',
          disabled: true,
          rules:[]
        },
        {
          type: 'SELECT',
          label: '关怀方式',
          fieldName: 'remindWay',
          initialValue: '',
          itemList: this.createDictList('8208'),
          rules: [{ required: true, message: '请选择关怀方式' }]
        },
        {
          type: 'INPUT',
          label: '其他建议',
          fieldName: 'customerFeedback',
          selfCols: 3,
          style: { height: '50px' }
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          selfCols: 3,
          style: { height: '50px' }
        }
      ];
    },
    // 查询所有车系(供table使用)
    async querySeries() {
      const res = await getSeries();
      this.vehicle.find(x => x.dataIndex === 'SERIES').editItems = res.data.map(x => ({ text: x.SERIES_NAME, value: x.SERIES_ID + '' }));
    },
     // 查询所有车型(供table使用)
    async queryModel() {
      const res = await getModel();
      this.vehicle.find(x => x.dataIndex === 'MODEL').editItems = res.data.map(x => ({ text: x.MODEL_NAME, value: x.MODEL_ID + '' }));
    },
    selectChangeGh(val){
      if(val==10041001){
        this.formList1.find(item => item.fieldName === 'nextDate').rules=[{ required: true, message: '请选择下次关怀日期' }];
        this.formList1.find(item => item.fieldName === 'nextDate').disabled = false;
      } else {
        this.formList1.find(item => item.fieldName === 'nextDate').disabled = true;
        this.formList1.find(item => item.fieldName === 'nextDate').initialValue='';
        this.formList1.find(item => item.fieldName === 'nextDate').rules=[];
      }
    },
    // 保存
    async save() {
      this.saveData = this.$refs.formList1.SUBMIT_FORM(); // FormPanel ref 值
      if (this.saveData !== null) {
        if (this.confirmBtnLoading) return;
        this.confirmBtnLoading = true;
        this.remindData.url = this.ctiUrl;
        this.remindData.callid = this.callid
        window.console.log(this.remindData);
        let res = Object.assign({}, this.remindData,{url:this.ctiUrl},{callid:this.callid});
        window.console.log(res);
        // let res = Object.assign({}, this.remindData,{url:this.ctiUrl,callid:this.callId});
        this.formList1.forEach(x => {
          if (x.initialValue) {
            let resd = JSON.parse(`{"${x.fieldName}":"${x.initialValue}"}`);
            res = Object.assign(res, resd);
          }
        });
        if (this.type === 'add') {
            res = await saveRemind(res);
        }
        if(this.type === 'edit'){
          let objedit = Object.assign(res,{remindId:this.remindId});
          res = await saveRemind(objedit);
        }
        this.confirmBtnLoading = false;
        if (res.resultCode == '200') {
          this.$notify({
            title: '成功',
            message: '关怀成功',
            type: 'success'
          });
          this.closeDialog('refresh');
        }
      }
    },
    closeDialog(param) {
      this.$emit('close',param);
    },
    async selectList() {
      let infodata = await getOwnerVehicle(this.ownerNo);
      if (infodata.resultCode === 200) {
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(infodata.data);
      } else {
        this.$notify.error({ title: '提示信息', message: res.errMsg || '单据查询失败!' });
      }
    },
    // 呼出系统
    exhale(a) {
        let phone = a + this.remindData.phone; // 车主电话
        let userData = {
            userData: {
                // RO_NO: val.RO_NO,
                OWNER_CODE: this.remindData.ownerCode,
                OWNER_NAME: this.remindData.cusName,
                date: moment().format('YYYY-MM-DD hh:MM:SS')
            }
        };
        if (CallCenter.isLogin()) {
            CallCenter.callout(phone, null, null, null, null, userData);
            // this.roNo = val.RO_NO;
        } else {
            this.$notify.warning({ title: '提示信息', message: '没有外呼权限!' });
        }
    },
    after() {
      let that=this;
      CallCenter.addEventListener('after', function(json) {
          console.log("验证是否监听到了after方法=============================>true");
          console.log("返回值================================>begin");
          console.log("返回值录音第一段================================>",json.recordDownloadUrl);
          console.log("返回值录音第二段================================>",json.mediano);
          console.log("返回值录音第三段================================>",json.filename);
          let url = json.recordDownloadUrl + '/' + json.mediano + '?file=' + json.filename;
          console.log("返回值录音路径================================>",url);
          let getCallId = json.callid;
          console.log("返回值CALLID================================>",getCallId);
          that.ctiUrl=url;
          console.log("返回URL值录音后台传递================================>",that.ctiUrl);
          that.callid = getCallId;
          console.log("返回CALLID值录音后台传递================================>",that.callid);
      });
    }
  }
};
</script>
